home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1996 January / macformat-033.iso / mac / Shareware City / Developers / VideoToolbox / VideoToolboxSources / GDVideo.c < prev    next >
Encoding:
Text File  |  1995-10-27  |  75.6 KB  |  2,017 lines  |  [TEXT/CWIE]

  1. /* 
  2. GDVideo.c
  3. Copyright © 1989-1995 Denis G. Pelli
  4.  
  5. Complete set of routines to control video drivers directly, bypassing
  6. QuickDraw's Color and Palette Managers. There is a separate function call for
  7. each of the Control and Status Calls (csc) implemented by video drivers. They
  8. are described in Designing Cards and Drivers, 3rd Ed., chapter 9. A few new
  9. calls are documented in the Display Device Driver Guide Developer Note, which
  10. appeared on the January '94 Developer CD.
  11.  
  12. This file also contains several other helpful routines that deal with video
  13. device drivers. For background, read “Video synch”.
  14.  
  15. THE MORE-USEFUL (HIGH-LEVEL) ROUTINES: (in alphabetical order)
  16.  
  17. char *GDCardName(GDHandle device);
  18. Returns the address of a C string containing the name of the video card. You
  19. should call DisposePtr() on the returned string when you no longer need it.
  20. Takes about 1.5 ms because Apple's slot routines are very slow. 
  21.  
  22. short GDClutSize(GDHandle device);
  23. Returns the number of entries in the video driver's clut in the current video
  24. mode (i.e. current pixel size). VideoToolbox.h defines a preprocessor macro
  25. GDCLUTSIZE(device) that expands to equivalent inline code.
  26.  
  27. long GDColors(GDHandle device)
  28. Number of colors, in the current mode.
  29.  
  30. short GDDacSize(GDHandle device)
  31. Figures out how many bits in the video dac.
  32.  
  33. OSErr GDSetDelay(GDHandle device,Boolean dontWaitForVBL,double nanoseconds);
  34. OSErr GDGetDelay(GDHandle device,Boolean *dontWaitForVBLPtr,double *nanosecondsPtr);
  35. These two routines support features, i.e. cscSetTimeDelays and cscGetTimeDelays, 
  36. unique to the built-in video driver of the
  37. PowerMac 7500 and 8500. Both routines will merely return innocuous errors (-17
  38. and -18) if used with any other video driver. Like most video drivers, the
  39. 7500/8500 video driver normally waits for VBL when loading the CLUT, but this can
  40. be overriden by the Boolean parameter dontWaitForVBL, in which case, from then on
  41. (until it's changed again or the machine is rebooted) the driver will load the
  42. CLUT immediately when it's called, without waiting for VBL. The second feature is
  43. that the video driver normally waits 800 ns after loading each RGB triplet to the
  44. CLUT, "to allow for the CLUT to settle and increment its address", and that time
  45. can be set by the parameter "nanoseconds". GDGetDelay() allows you to read the
  46. current setting of both parameters. GDSetDelay() allows you to set both
  47. parameters. If the supplied value of "nanoseconds" is infinite or NAN then it's
  48. ignored and only "dontWaitForVBL" is set. The 7500/8500 video driver was written
  49. by Apple Engineer Fernando Urbina, nano@apple.com. GDSetDelay() and GDSetDelay()
  50. were written by Denis Pelli, to allow convenient access to Fernando's custom
  51. control and status driver calls. Note that Fernando Urbina has also supplied a
  52. newer version of this driver (included in the VideoToolbox) that supports several
  53. extra resolutions, of which the most noteworthy is 640x480x120 Hz, which works
  54. well on the Apple 17" Multiscan.
  55.  
  56. Thus far, using visual inspection in TimeVideo, I've been unable to notice any
  57. bad effects of not waiting for VBL and reducing the waiting interval from 800 ns
  58. to zero. I asked Fernando Urbina, nano@apple.com, about it, since he put in the
  59. delays because he "does indeed get artifacts when updating the CLUT if we don't
  60. suppress interrupts while updating it." What were the artifacts? Fernando
  61. replies, "The delays are there because of hardware requirements:  When writing to
  62. the CLUT in a self-incrementing mode the hardware requires 800ns to update the
  63. address counter.  Of course, this is worst case.  ( We write the CLUT starting
  64. address and then the R, G, and B.  At the end of the B, the address counter for
  65. the CLUT will automatically increment to the next address.) I noticed some
  66. artifacts when doing palette animation -- one of the After Dark modules showed
  67. this very well."
  68.  
  69. OSErr GDGetDisplayMode(GDHandle device,unsigned long *displayModeIDPtr
  70.     ,unsigned short *modePtr,unsigned short *pagePtr,Ptr *baseAddrPtr);
  71. Calls cscGetCurMode, documented in Apple's new Display Device Driver Guide
  72. Developer Note on the January '94 Developer CD. The "display mode ID" is a new
  73. parameter, to support multi-resolution displays. Each display mode may have
  74. multiple pixel depths (which, confusingly, have also been called "modes"). This
  75. call will only be useful if the Display Manager is present (requires PowerPC or
  76. System 7.5) and if you're using the Display Manager, which is documented in a
  77. chapter in Inside Macintosh:Advanced Color Imaging, which thus far has appeared
  78. only in draft form on the December '94 Developer CD. The call returns an error
  79. if the video driver does not support the Display Manager. UNTESTED!!
  80.  
  81. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table);
  82. Calls cscGetEntries. This is much as you'd expect after reading GDSetEntries
  83. below. Note that unless the gamma table is linear, the values returned may not
  84. be the same as those originally passed by GDSetEntries. So call
  85. GDUncorrectedGamma first. Try the demo TimeVideo.
  86.  
  87. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle);
  88. Calls cscGetGamma. Returns a pointer to the Gamma table in the specified video
  89. device. (I.e. you pass it a pointer to your pointer, a handle, which it uses to
  90. load your pointer.)
  91.  
  92. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr);
  93. Calls cscGetPageCnt. Called "GetPages" in Designing Cards and Drivers, 3rd Ed.
  94. You tell it which mode you're interested in. It tells you how many pages of
  95. video ram are available in that mode.
  96.  
  97. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  98. Returns 0 if no such video mode, returns 1 if mode is available.
  99. If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  100. If pagesPtr is not NULL, then sets *pagesPtr to pages.
  101.  
  102. unsigned char *GDName(GDHandle device);
  103. Returns a pointer to the name of the driver (a pascal string). This is quick.
  104. The string is part of the driver itself, so don't modify it or try to dispose of it.
  105.  
  106. unsigned char *GDNameStr(GDHandle device);
  107. Returns a pointer to the name of the driver, as a C string. 
  108. The string is static, and will be overwritten by the next call to GDNameStr().
  109.  
  110. ColorSpec *GDNewLinearColorTable(GDHandle device);
  111. Creates a default table for use when gdType==directType.
  112.  
  113. OSErr GDPrintGammaTable(FILE *o,GDHandle device);
  114.  
  115. OSErr GDRestoreDeviceClut(GDHandle device);
  116. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  117. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  118. whereas this routine always works. Passing a NULL argument causes restoration of
  119. cluts of all video devices.
  120.  
  121. OSErr GDSaveGamma(GDHandle device);
  122. OSErr GDRestoreGamma(GDHandle device);
  123. Use an internal cache to save and restore the device's gamma-correction table. 
  124. GDSaveGamma(NULL) and GDRestoreGamma(NULL) save and restore ALL devices.
  125. After the first request, GDSaveGamma() ignores subsequent requests to save the same 
  126. device's gamma table. GDRestoreGamma() no longer discards the saved copy (the cache), so multiple
  127. calls to GDRestoreGamma() will all be effective. You should call
  128. GDRestoreGamma before GDRestoreDeviceClut, because the video driver merely saves the gamma
  129. table when you do a cscSetGamma; the driver actually uses the gamma table to transform
  130. a new clut only when loading the clut.
  131.  
  132. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  133. Does a cscSetEntries call to the video card's driver, loading any
  134. number of clut entries with arbitrary rgb triplets. (Note that the driver will
  135. transform your rgb triplets via the gamma table before loading them into the
  136. clut; so call GDUncorrectedGamma first.) "device" specifies which video device's
  137. clut you want to load. "start" is either in the range 0 to clutSize-1,
  138. indicating which clut entry to load first (in "sequence mode"), or is -1
  139. (requesting "index mode"). "count" is the number of entries to be modified,
  140. minus 1. "table" is a ColorSpec array (not a ColorTable) containing the rgb
  141. triplets that you want to load into the clut. In sequence mode "start" must be
  142. in the range 0 to clutSize-1, the i-th element of table corresponds to the
  143. i+start entry in the clut, and the "value" field of each element of table is
  144. ignored. In index mode "start" must be -1, and the "value" field of each element
  145. of table indicates which clut entry to load it into. The arguments start, count,
  146. and table are the same as for the Color Manager call SetEntries(), documented in
  147. Inside Macintosh V-143. (Most drivers wait for blanking before modifying the
  148. clut. For a full discussion, read the VideoToolbox "Video synch" file.) You may
  149. also want to look at the file SetEntriesQuickly.c, which provides the
  150. functionality of GDSetEntries and GDDirectSetEntries, but bypasses the video
  151. driver to access the hardware directly.
  152.  
  153. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table);
  154. Checks the (**device).gdType field and calls cscSetEntries, cscDirectSetEntries,
  155. or nothing, as appropriate.
  156.  
  157. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  158.     ,ColorSpec *table);
  159. Calls GDSetEntriesByType() while the processor priority has been temporarily 
  160. raised to 7.
  161.  
  162. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma);
  163. Calls cscSetGamma. Loads a Gamma table into the specified video device. The
  164. video driver will make a copy of your table. You can discard your table after
  165. making this call. Note that the video driver only uses the gamma table when
  166. performing SetEntries, i.e. when actually loading the clut. The structure of the
  167. gamma table is (finally!) documented in Designing Cards and Drivers, 3rd
  168. edition, pages 215-216. Beware of a discrepancy between the documentation and
  169. the definition in QuickDraw.h: gFormulaData is described as a byte array in the
  170. text, but is declared as a short array in the QuickDraw.h header file. NOTE: a
  171. few video drivers (Radius PowerView and SuperMac ColorCard) do not support gamma
  172. tables. The SuperMac ColorCard is well behaved, giving the appropriate error
  173. code, returned by GDSetGamma and GDGetGamma. The Radius PowerView reports no
  174. error yet ignores the GDSetGamma call and returns a table full of zeroes in
  175. response to GDGetGamma. See NOTE from Tom Busey below. However, if all you want
  176. to do is call GDUncorrectedGamma, then these limitations won't affect you,
  177. because the drivers that lack gamma tables always give you precisely the
  178. behaviour that one requests by calling GDUncorrectedGamma.
  179.  
  180. OSErr GDSetPageDrawn(GDHandle device,short page);
  181. Choose which page of video memory will be used by future drawing operations. 
  182. Untested.
  183.  
  184. OSErr GDSetPageShown(GDHandle device,short page);
  185. Choose which page of video memory we see. Untested.
  186.  
  187. OSErr GDUncorrectedGamma(GDHandle device);
  188. Asks GDSetGamma to load a linear gamma table, i.e. no correction. (The gamma
  189. correction implemented by table-lookup in the video driver is too crude for
  190. experiments that want accurate luminance control.)
  191.  
  192. int GDVersion(GDHandle device)
  193. Returns the version number of the driver. From the first word-aligned word after
  194. the name string. This is quick.
  195.  
  196. OSErr GDGetNextResolution()
  197. Implements cscGetNextResolution.
  198.  
  199. LESS-USEFUL (LOW LEVEL) ROUTINES:
  200.  
  201. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  202. Uses low-level PBControl() call to implement a "Control()" call that works! 
  203. I don't know why this wasn't discussed in Apple Tech Note 262.
  204.  
  205. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table);
  206. Calls cscDirectSetEntries. If your pixel depth is >8 then the cscSetEntries call is
  207. disabled, and you must use this instead of GDSetEntries().
  208.  
  209. VideoDriver *GDDriverAddress(GDHandle device);
  210. Returns a pointer to the driver, whether in ROM or RAM. Neither this prototype
  211. nor the definition of the VideoDriver structure are included in VideoToolbox.h.
  212.  
  213. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  214. Calls cscGetDefaultMode. It tells you what the default mode is. I'm not sure
  215. what this means.
  216.  
  217. OSErr GDGetGray(GDHandle device,Boolean *flagPtr);
  218. Calls cscGetGray. Get gray flag. 0 for color. 1 if all colors mapped to
  219. luminance-equivalent gray tones.
  220.  
  221. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr);
  222. Calls cscGetInterrupt. Get flag. 1 if VBL interrupts of this card are enabled. 0
  223. if disabled.
  224.  
  225. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr);
  226. Calls cscGetMode. It tells you the current mode, page of video memory, and the
  227. base address of that page.
  228.  
  229. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr);
  230. Calls cscGetPageBase. (Called "cscGetBaseAddr" in Designing Cards and Drivers, 3rd
  231. Ed.) You tell it which page of video memory you're interested in (in the current
  232. video mode). It tells you the base address of that page.
  233.  
  234. OSErr GDGrayPage(GDHandle device,short page);
  235. Calls cscGrayPage. (Called "cscGrayScreen" in Designing Cards and Drivers, 3rd
  236. Ed.) Fills the specified page with gray, i.e. the dithered desktop pattern. I'm
  237. not aware of any particular advantage in using this instead of FillRect().
  238. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  239. devices, i.e. >8 bit pixels, the driver will also load a linear,
  240. gamma-corrected, gray color table.
  241.  
  242. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr);
  243. Calls cscReset. Initialize the video card to its startup state, usually 1 bit
  244. per pixel. Returns the parameters of that state.
  245.  
  246. OSErr GDSetDefaultMode(GDHandle device,short mode);
  247. Calls cscSetDefault. Supposedly, you tell it what mode you want to start up with
  248. when you reboot. (I've never been able to get this to work. No error and no
  249. effect. Perhaps I've misunderstood its purpose.)
  250.  
  251. OSErr GDSetGray(GDHandle device,Boolean flag);
  252. Calls cscSetGray. Set gray flag. 0 for color. 1 if all colors mapped to
  253. luminance-equivalent gray tones.
  254.  
  255. OSErr GDSetInterrupt(GDHandle device,Boolean flag);
  256. Calls cscSetInterrupt. Set flag to 1 to enable VBL interrupts of this card, or 0
  257. to disable.
  258.  
  259. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr);
  260. Calls cscSetMode. You tell it what mode and video page you want. It sets 'em and
  261. returns the base address of that page in video memory. Also, because Apple said
  262. so, the video driver sets the entire clut to 50% gray. Note that this changes
  263. things behind QuickDraw's back. For most applications life will be simpler if
  264. you overtly ask QuickDraw to take charge by calling Apple's SetDepth() instead
  265. of GDSetMode(). WARNING: Apple now considers the mode numbers merely ordinal.
  266. E.g. on the 8•24 video card the 32-bit mode has mode number 0x84, not 0x85 as
  267. you might have expected on the basis of old Apple documentation and other Apple
  268. video cards.
  269.  
  270. OSErr GDSwitchMode(GDHandle device,short mode,long displayModeID,short page,Ptr *baseAddrPtr);
  271. Calls cscSwitchMode as documented in Designing PCI Video Cards and Drivers. PCI
  272. video drivers are required to support this call. It's like GDSetMode, but additionally
  273. allows you to specify the displayModeID, which determines the spatial resolution.
  274.  
  275. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  276. Uses low-level PBStatus() call to implement a "Status()" call that works! The
  277. need for this is explained in Apple Tech Note 262, which was issued in response
  278. to my bug report in summer of '89.
  279.  
  280. PatchMacIIciVideoDriver();
  281. Fixes a crashing bug in the Mac IIci built-in video driver's implementation of
  282. cscGetEntries. The patch persists until reboot. It is unlikely that you will need
  283. to call this explicitly, PatchMacIIciVideoDriver() is automatically invoked the
  284. first time GDGetEntries is called. The Mac IIci built-in video driver
  285. (.Display_Video_Apple_RBV1 driver, version 0) has a bug that causes it to crash
  286. if you try to do a GetEntries Status request. PatchMacIIciVideoDriver() finds and
  287. patches the copy of the buggy driver residing in memory. (If the driver is
  288. ROM-based it first moves it to RAM, and then patches that.) Only two instructions
  289. are modified, to save & restore more registers. This fix persists only until the
  290. next reboot. If the patch is successfully applied the version number is increased
  291. by 100.
  292.  
  293. NOTES:
  294.  
  295. Several bugs in version 2 (in System ≤6.03) of the video driver for Apple's
  296. "Toby Frame Buffer" video card that affected use of the GetGamma call were
  297. fixed in version 3 (in System 6.04), apparently in response to my bug report to
  298. Apple.
  299.  
  300. The control/status-call parameter in a GDControl or GDStatus call specifies what
  301. you want done. See Designing Cards and Drivers, 3rd Edition, Chapter 9. (A few
  302. new calls are documented in the Display Device Driver Guide Developer Note.)
  303.  Note that sometime around 1990 Apple renamed some of the Control and Status
  304. calls, giving them names that better reflect their function. I followed suit.
  305. However, Apple neglected to update their book, Designing Cards and Drivers, now
  306. in its 3rd edition. Fortunately, they define both names in their Video.h header
  307. file. To avoid confusion, here are the equivalences. Note that "csc" stands for
  308. "Control and Status Call"
  309. Control call:
  310.  cscGrayPage =  cscGrayScreen = 5
  311. Status calls:
  312.  cscGetPageCnt = cscGetPages = 4
  313.  cscGetPageBase = cscGetBaseAddr = 5
  314.  
  315. Based on:
  316. Inside Macintosh-II (Device Manager)
  317. Designing Cards and Drivers, 3rd Edition, Chapter 9.
  318. Display Device Driver Guide Developer Note on the January '94 Developer CD.
  319. Tech Note 262: "Controlling Status Calls"
  320. "GreyScale Information" from AppleLink "Apple Technical Info"
  321. "Video Configuration ROM Software Specification" also from AppleLink,
  322. in "Developer Tech Support:Macintosh:32 Bit QuickDraw"
  323.  
  324. NOTES:
  325. Tom Busey (busey@indiana.edu) writes: "I'm using an 8-bit SuperMac ColorCard
  326. that a used computer dealer gave me when I ordered a Toby card. I discovered
  327. that the status and control calls for GDUncorrectedGamma return -17 and -18
  328. respectively, which means that the driver doesn't support different gammas.
  329. GDUncorrectedGamma returns an error message, but GDOpenWindow doesn't use the
  330. error message or pass it back to the calling program. I'm wondering if there are
  331. people using GDOpenWindow who think that they are getting a linear gamma but who
  332. are actually getting an error message and not learning about it."
  333.      Tom's facts are right, but he needn't worry. A few video drivers, e.g.
  334. Radius PowerView, and apparently the SuperMac ColorCard, don't implement gamma
  335. tables at all, but the error from GDUncorrectedGamma is probably not a concern.
  336. The real test is to run TimeVideo. TimeVideo does a write-and-read-back test of
  337. the clut of your video card. If that test passes then you can safely conclude
  338. that there's no gamma translation going on. So, as nearly every document in the
  339. VideoToolbox says: run TimeVideo and read the report.
  340.      Here's how gamma tables work. According to the Apple manual (Designing
  341. Cards and Drivers), the values in the rgb triplets that you supply in a
  342. cscSetEntries call to the video driver are first translated via the gamma table
  343. (each r,g, and b component separately) before being loaded into the CLUT
  344. hardware table. Most drivers maintain a gamma table internally (in computer
  345. memory) and allow you to get and set it via the cscGetGamma and cscSetGamma
  346. calls. A few video drivers (Radius PowerView, SuperMac ColorCard) don't support
  347. gamma tables. They load your rgb values directly into the CLUT, without
  348. translation. However, for users of the VideoToolbox that's usually fine, since
  349. that's exactly the behavior that we routinely request by calling
  350. GDUncorrectedGamma. Of course, if you want to load a custom gamma table, other
  351. than the identity transformation, then you'll be calling GDSetGamma, and you
  352. should make sure it does not return an error. (Alas, the Radius PowerView driver
  353. more or less ignores the cscSetGamma and cscGetGamma requests--GDGetGamma
  354. returns a table that's all zeroes--but the driver fails to report an error. I
  355. wrote to the Radius programmer a year ago, but they're no longer interested in
  356. working on that product.)
  357.     Patrick Flanagan (flanagan@deakin.edu.au) writes: "Can I be 100% sure, if I
  358. select "Special Gamma", in the Monitors Control Panel and choose "uncorrected
  359. gamma" for a video card, that this is the same as using GDUncorrectedGamma?"
  360. REPLY: That is what I would expect from reading all the relevant documentation.
  361. However, to be 100% certain of anything I would want to check it myself.
  362. TimeVideo calls GDUncorrectedGamma and then confirms that write-then-read tests
  363. of the CLUT return what was written. (Gamma-table translation is only done on
  364. the write, not undone on the read.) Thus TimeVideo will confirm for you that
  365. after calling GDUncorrectedGamma your video card has what Apple calls an
  366. "uncorrected" gamma table. However, TimeVideo does not check what you would get
  367. by merely selecting "uncorrected" gamma in the Monitors Control Panel. It would
  368. be reasonable to assume that you would get the same result since Monitors
  369. interacts with the video driver by the same Control and Status Calls as
  370. GDVideo.c does, so it must use the same cscSetGamma call as is used by
  371. GDUncorrectedGamma.
  372.  
  373. HISTORY:
  374. 9/29/89     dgp    added caution above that successive calls to SetEntries may be on one 
  375.                 frame.
  376. 11/21/89    dgp    corrected mode list: 0x80... as pointed out by Chuck Stein
  377. 11/30/89    dgp    added note above from Don Kelly.
  378.                 Added cautionary note above about GDSetEntries().
  379. 3/1/90        dgp    updated comments.
  380. 3/3/90        dgp    included Video.h instead of defining VDSetEntryRecord and VDPageInfo.
  381. 3/20/90        dgp    made compatible with MPW C.
  382. 3/23/90        dgp    changed char to unsigned char in VDDefModeRec
  383.                 and VDFlagRec to prevent undesirable sign extension.
  384. 4/2/90        dgp    Deleted mode argument from GDGrayScreen().
  385. 7/28/90        dgp Fixed stack overflow in GDGrayScreen, by declaring SysEnvRec static.
  386. 10/20/90    dgp    Apple has renamed the control and status calls, so I followed suit:
  387.                 •GDGetPageBase replaces GDGetBaseAddr
  388.                 •GDReset replaces GDInit
  389.                 •GDGrayPage replace GDGrayScreen
  390.                 •GDGetPageCnt replaces GDGetPages
  391. 2/12/91        dgp Discovered that the old bug in GDGrayPage is still present in System
  392.                 6.05, so I removed the conditional around the bug fix. TestGDVideo
  393.                 now works with: Mac II Video Card, Mac II Display Card (4•8), 
  394.                 Mac IIci Built-in Video, TrueVision NuVista, Mac IIsi Built-in Video.
  395. 7/22/91        dgp    Changed definition of csGTable from GammaTblPtr to Ptr, 
  396.                 to conform with MPW C.
  397. 8/24/91        dgp    Made compatible with THINK C 5.0.
  398. 10/22/91    dgp    With help from Bart Farell, converted all functions headers to
  399.                 Standard C style.
  400. 8/26/92        dgp    added a few miscellaneous comments
  401.                 In all routines, *baseAddrPtr is now set only if baseAddrPtr is not NULL.
  402. 10/10/92    dgp    Added GDRestoreDeviceClut(). Removed obsolete support for THINK C 4.
  403. 11/30/92    dgp corrected error in comment documenting values of argument to GDSetGray().
  404.                 Set flag to zero for color,1 for luminance-mapped gray.
  405. 12/9/92        dgp    Enhanced GDRestoreDeviceClut(). Passing a NULL argument now requests
  406.                 application to all devices. I only just learned that Apple's
  407.                 RestoreDeviceClut() behaves in this way.
  408. 12/15/92    dgp Renamed GDRestoreDeviceClut to GDRestoreDeviceClut to be consistent
  409.                 with Apple's capitalization of RestoreDeviceClut.
  410. 12/16/92    dgp Updated comments to be consistent with 3rd edition of Designing Cards
  411.                 and Drivers. •Renamed myGDHandle to "device", which is easier to read.
  412.                 Renamed GDLinearGamma to GDUncorrectedGamma, and generalized it
  413.                 to work with any size DAC. For compatibility with old programs
  414.                 VideoToolbox.h now has a #define statement making GDLinearGamma
  415.                 an alias for GDUncorrectedGamma.
  416. 12/30/92    dgp Updated some of the comments. Eliminated Files.h.
  417. 12/30/92    dgp Use GDClutSize() to determine clut size.
  418. 1/4/93        dgp In GDClutSize, check for fixedType.
  419. 1/5/93        dgp In GDClutSize, only set last clut entry.
  420.                 Added PatchMacIIciVideoDriver() to the end of this file, and 
  421.                 automatically invoke it the first time GDGetEntries is called.
  422. 1/6/93        dgp    Cleaned up GDClutSize. It now seems to work correctly in the direct modes.
  423. 1/18/93    dgp    Spruced up the documentation.
  424.             •Added all the code formerly in GDIdentify.c, but omitted the obsolete 
  425.             function GDIdentify(), which simply printed GDName() and GDVersion.
  426.             •Enhanced GDGetEntries() to avoid calling drivers that are known
  427.             to crash, returning a statusErr instead.
  428.             •Recoded PatchMacIIciVideoDriver() so as not to call GetScreenDevice.c.
  429. 2/1/93    dgp    Fixed endless loop in PatchMacIIciVideoDriver. Enhanced to deal with
  430.             ROM-based drivers as well.
  431. 2/5/93    dgp    Expanded the documentation of GDSetEntries above, and supplied sample
  432.             code showing how to load the clut.
  433. 2/7/93    dgp Fixed endless loop in PatchMacIIciVideoDriver.
  434. 2/20/93    dgp    Fixed bug in GDUncorrectedGamma() that was causing TestCluts to fail
  435.             for video devices that have nonstandard gamma tables. 
  436. 3/18/93    dgp    Fixed divide by zero error in GDClutSize.
  437. 4/6/93    dgp    GDGetPageCnt() now sets *pagePtr argument only if no error occurs.
  438.             Deleted GDModeName(). Removed assumption, in all routines, that there
  439.             is any particular correspondence between the video mode number and
  440.             the pixel size. Added two new routines, GDPixelSize and GDType,
  441.             that return the pixelSize and gdType (i.e. fixedType, clutType, or 
  442.             directType) of the device. Completely rewrote GDClutSize.
  443. 4/16/93    dgp    Streamlined GDClutSize() to make it fast enough for routine use.
  444. 4/19/93    dgp    Added GDNewLinearColorTable.
  445. 4/25/93    dgp    Made CntrlParam automatic instead of static.
  446. 4/25/93    dgp    Added GDColors(device) and GDPrintGammaTable(). Alphabetized the lists
  447.             of functions in the documentation above.
  448. 5/11/93    dgp    Changed GDPrintGammaTable() to accept a simple file pointer instead of
  449.             an array of two file pointers.
  450. 7/7/93    dgp enhanced GDDacSize() to return 8 unless the gamma table is present and
  451.             reasonable.
  452. 7/29/94    dgp    added GDNameStr().
  453. 9/5/94 dgp removed assumption in printf's that int==short.
  454. 10/25/94 dgp check for missing driver, (*device)->gdRefNum==0, and treat that case
  455.             just like  device==NULL. Devices created by NewGWorld have no driver.
  456. 12/29/94 dgp added GDGetDisplayMode(), calls cscGetCurMode, based on Apple's new
  457.             Display Device Driver Guide Developer Note on the January '94 Developer CD.
  458. 1/15/94 dgp GDPixelSize if supplied with a merely device record, with no associated 
  459.             device driver, then we just return (**(**device).gdPMap).pixelSize
  460. 3/22/95 dgp Added .Display_Video_Apple_DOMEMax to the list of drivers that don't
  461.             support cscGetEntries. Crash reported by Greg Jackson.
  462. 4/6/95 dgp Changed GDUncorrectedGamma() to pass a NULL gamma table pointer instead of
  463.             a linear gamma table, in the hopes that this might work even with the
  464.             few video drivers that don't fully support cscSetGamma.
  465. 4/21/95 dgp Fixed conditionals to cope with various versions of Video.h
  466. 6/8/95 dgp Made sure that the Mac structs are always 68k aligned.
  467. 6/26/95 dgp fixed error in dealing with UNIVERSAL_HEADERS==1 reported by Bart Farell.
  468.         We need the typedefs for DisplayModeID and DepthMode for universal headers
  469.         absent and also for version 1.
  470. 6/27/95 dgp Same for enum cscGetNextResolution.
  471. 6/30/95 dgp GDSaveGamma(NULL) and GDRestoreGamma(NULL) now save and restore ALL devices.
  472. 7/3/95 dgp After the first request, GDSaveGamma() ignores subsequent requests to save the same 
  473.         device's gamma table. GDRestoreGamma() no longer discards the saved copy, so multiple
  474.         calls to GDRestoreGamma() will all be effective. The effect of these changes is that
  475.         if you have multiple nested pairs of calls to GDSaveGamma and GDRestoreGamma, you will
  476.         end up with the desired result: every RestoreGamma will restore the screen to its
  477.         original gamma, same as it had at the time of the first call to GDSaveGamma.
  478. 8/10/95 bt & dgp. Bosco Tjan, tjan@cs.umn.edu, found that the conditionals needed to be 
  479.         adjusted to be compatible with Symantec C 8, because their Video.h is different from Apple's.
  480. 9/26/95 dgp. For compatibility with the ETO18 (CW7) universal headers, eliminated the now obsolete
  481.         typedefs of DepthMode (unsigned short) and DisplayModeID (unsigned long).
  482. 10/4/95 dgp Added code to GDCardName() to check for the presence of the Slot Manager, and
  483.         just return an empty string "" if it's not present. This will prevent crashes on PCI Macs.
  484. 10/4/95 dgp Added GDSwitchMode() which implements cscSwitchMode as documented in Designing PCI 
  485.         Video Cards and Drivers.
  486. 10/24/95 dgp Added GDGetDelay and GDSetDelay to implement the custom video driver calls
  487.         offered by the 7500/8500 video driver.
  488. 10/25/95 dgp After clarification from Fernando, fixed bug in GDGetDelays, so it should
  489.         now work reliably. I didn't know that I had to set the validMask bits.
  490. */
  491.  
  492. #include "VideoToolbox.h"
  493. #include <ROMDefs.h>    // catDisplay,typeVideo,sRsrcName,sGammaDir
  494. //#include <Displays.h>
  495. void GetCPUProperties(char *cpuName,long *cpuHz,Boolean *hasL2Cache);
  496. void GetVideoProperties(GDHandle device,char *slotName,char *cardName,char *modelName);
  497.  
  498.  
  499. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  500.     #pragma options align=mac68k
  501. #endif
  502.  
  503. #if !UNIVERSAL_HEADERS
  504.     /* these declarations appear in Video.h, universal version 1 and later */
  505.     struct VDSwitchInfoRec{
  506.         unsigned short csMode;
  507.         unsigned long csData;
  508.         unsigned short csPage;
  509.         Ptr csBaseAddr;
  510.         unsigned long csReserved;
  511.     };
  512.     typedef struct VDSwitchInfoRec VDSwitchInfoRec;
  513.     enum{cscGetCurMode=10};
  514. #endif
  515. #if UNIVERSAL_HEADERS<2
  516.     enum{dRAMBasedMask=0x0040};    /* dCtlDriver is a handle (1) or pointer (0) */
  517.     typedef unsigned long UInt32;
  518. #endif
  519. #if UNIVERSAL_HEADERS<2 || SYMANTEC_C || __MWERKS__>=0x700
  520.     /* These declarations appeared in Apple's Video.h, universal version 2.0a3, */
  521.     /* and in "Universal Interfaces  DDK v23c5.  Monday, May 15, 1995"
  522.     /* but not in previous or subsequent versions (e.g. 2.1 aka ETO18). */
  523.     struct VDResolutionInfoRec {
  524.         unsigned long                    csPreviousDisplayModeID;    /* ID of the previous resolution in a chain */
  525.         unsigned long                    csDisplayModeID;            /* ID of the next resolution */
  526.         unsigned long                    csHorizontalPixels;            /* # of pixels in a horizontal line */
  527.         unsigned long                    csVerticalLines;            /* # of lines in a screen */
  528.         Fixed                            csRefreshRate;                /* Vertical Refresh Rate in Hz */
  529.         unsigned short                    csMaxDepthMode;                /* 0x80-based number representing max bit depth */
  530.         unsigned long                    csResolutionFlags;            /* flag bits */
  531.         unsigned long                    csReserved;                    /* Reserved */
  532.     };
  533.     typedef struct VDResolutionInfoRec VDResolutionInfoRec;
  534.     typedef VDResolutionInfoRec *VDResolutionInfoPtr;
  535.     enum{cscGetNextResolution=17};
  536. #endif
  537.  
  538. typedef struct VDFlagRec {
  539.     unsigned char flag;
  540.     char pad;
  541. } VDFlagRec;
  542.  
  543. typedef struct VDDefModeRec{
  544.     unsigned char spID;
  545.     char pad;
  546. } VDDefModeRec;
  547.  
  548. typedef struct {
  549.     short flags;
  550.     short blanks[3];
  551.     short open;
  552.     short prime;
  553.     short control;
  554.     short status;
  555.     short close;
  556.     Str255 name;
  557. } VideoDriver;
  558. VideoDriver *GDDriverAddress(GDHandle device);
  559.  
  560. typedef struct {
  561.     short csCode;        // control code
  562.     short length;        // total parameter block bytes
  563.     char param[];        // control call data
  564. } ScrnCtl;
  565.  
  566. typedef struct {
  567.     short spDrvrHw;        // Slot Manager ID
  568.     short slot;            // Number of slot
  569.     long dCtlDevBase;    // Start of device's address space
  570.     short mode;            // screen characteristics
  571.     short flagMask;        // Which flag bits are used
  572.     short flags;        // device state: bit 0 = 0 = mono; bit 0 = 1 = color;
  573.                         // bit 11 =  1 = startup device; bit 15 = 1 = active
  574.     short colorTable;    // 'clut' id, default = -1
  575.     short gammaTable;    // Selects color intensity, default (MacII) = -1
  576.     Rect globalRect;    // global rectangle, main device topLeft = 0,0
  577.     short ctlCount;        // total control calls
  578.     ScrnCtl ctl;
  579. } Scrn;
  580.  
  581. typedef struct {
  582.     short scrnCount;    // Total devices
  583.     Scrn scrn;
  584. } Scrns;                // 'scrn' resource
  585.  
  586. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  587.     #pragma options align=reset
  588. #endif
  589.  
  590. Scrn **GDGetScrn(GDHandle device);
  591.  
  592. OSErr GDGetNextResolution(GDHandle device,unsigned long previousDisplayModeID
  593.     ,unsigned long *displayModeIDPtr,unsigned long *horizontalPixelsPtr
  594.     ,unsigned long *verticalLinesPtr,Fixed *refreshRatePtr
  595.     ,unsigned short *maxDepthModePtr);
  596.  
  597. OSErr GDGetDisplayMode(GDHandle device,unsigned long *displayModeIDPtr
  598.     ,unsigned short *modePtr,unsigned short *pagePtr,Ptr *baseAddrPtr)
  599. /*
  600. It tells you the current display mode, etc., but only if the video driver 
  601. supports the Display Manager.
  602. */
  603. {
  604.     VDSwitchInfoRec vdSwitchInfo;
  605.     int error;
  606.  
  607.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  608.     error=GDStatus((*device)->gdRefNum,cscGetCurMode,(Ptr) &vdSwitchInfo);
  609.     if(displayModeIDPtr!=NULL) *displayModeIDPtr=vdSwitchInfo.csData;
  610.     if(modePtr!=NULL) *modePtr=vdSwitchInfo.csMode;
  611.     if(pagePtr!=NULL) *pagePtr=vdSwitchInfo.csPage;
  612.     if(baseAddrPtr!=NULL) *baseAddrPtr=vdSwitchInfo.csBaseAddr;
  613.     return error;
  614. }
  615.  
  616. OSErr GDGetNextResolution(GDHandle device,unsigned long previousDisplayModeID
  617.     ,unsigned long *displayModeIDPtr,unsigned long *horizontalPixelsPtr
  618.     ,unsigned long *verticalLinesPtr,Fixed *refreshRatePtr
  619.     ,unsigned short *maxDepthModePtr)
  620. /*
  621. Tells you the next available displayModeID, after previousDisplayModeID.
  622. This is a new call, introduced for PCI video drivers.
  623. */
  624. {
  625.     VDResolutionInfoRec    vdSwitchInfo;
  626.     int error;
  627.  
  628.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  629.     vdSwitchInfo.csPreviousDisplayModeID=previousDisplayModeID;
  630.     error=GDStatus((*device)->gdRefNum,cscGetNextResolution,(Ptr) &vdSwitchInfo);
  631.     if(displayModeIDPtr!=NULL) *displayModeIDPtr=vdSwitchInfo.csDisplayModeID;
  632.     if(horizontalPixelsPtr!=NULL) *horizontalPixelsPtr=vdSwitchInfo.csHorizontalPixels;
  633.     if(verticalLinesPtr!=NULL) *verticalLinesPtr=vdSwitchInfo.csVerticalLines;
  634.     if(refreshRatePtr!=NULL) *refreshRatePtr=vdSwitchInfo.csRefreshRate;
  635.     if(maxDepthModePtr!=NULL) *maxDepthModePtr=vdSwitchInfo.csMaxDepthMode;
  636.     return error;
  637. }
  638.  
  639. OSErr GDSetPageDrawn(GDHandle device,short page)
  640. // Select a page of video memory to draw into.
  641. {
  642.     int error;
  643.     short flags;
  644.     Ptr baseAddr;
  645.     static long qD=-1;
  646.  
  647.     if(qD==-1)Gestalt(gestaltQuickdrawVersion,&qD);
  648.     error=GDGetPageBase(device,page,&baseAddr);
  649.     if(!error){
  650.         if(qD>=gestalt32BitQD){
  651.             flags=GetPixelsState((**device).gdPMap);
  652.             LockPixels((**device).gdPMap);
  653.         }
  654.         (**(**device).gdPMap).baseAddr=baseAddr;
  655.         if(qD>=gestalt32BitQD){
  656.             GDeviceChanged(device);
  657.             SetPixelsState((**device).gdPMap,flags);
  658.         }
  659.     }
  660.     return error;
  661. }
  662.  
  663. OSErr GDSetPageShown(GDHandle device,short page)
  664. // Select a page of video memory for display.
  665. {
  666.     int error;
  667.     short mode;
  668.  
  669.     error=GDGetMode(device,&mode,NULL,NULL);
  670.     if(error)return error;
  671.     return GDSetMode(device,mode,page,NULL);
  672. }
  673.  
  674. short GDType(GDHandle device)
  675. // Returns what would normally be in (**device).gdType, for occasions when
  676. // the GDevice record might be invalid because you called GDSetMode().
  677. {
  678.     int error;
  679.     static ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  680.  
  681.     error=GDSetEntries(device,0,0,&white);
  682.     if(!error)return clutType;
  683.     error=GDDirectSetEntries(device,0,0,&black);
  684.     if(!error)return directType;
  685.     return fixedType;
  686. }
  687.  
  688. short GDPixelSize(GDHandle device)
  689. // Returns what would normally be in (**(**device).gdPMap).pixelSize, for occasions
  690. // when the GDevice record might be invalid because you called GDSetMode().
  691. // Exception: if this is merely a device record, with no associated device driver,
  692. // then we just return (**(**device).gdPMap).pixelSize
  693. {
  694.     int error;
  695.     short mode;
  696.  
  697.     if((**device).gdRefNum==0)return (**(**device).gdPMap).pixelSize;
  698.     error=GDGetMode(device,&mode,NULL,NULL);
  699.     return GDModePixelSize(device,mode);
  700. }
  701.  
  702. short GDModePixelSize(GDHandle device,short mode)
  703. // Returns the pixelSize associated with a given video mode.
  704. // If you've changed the mode by calling GDSetMode and you're running a System 
  705. // older than 6.0.5 the answer may may be wrong for some of the newer video cards,
  706. // because they have ideosynchratic associations of video mode and pixel size.
  707. {
  708.     short j;
  709.     long version;
  710.  
  711.     if(mode==(**device).gdMode)return (**(**device).gdPMap).pixelSize;
  712.     Gestalt(gestaltSystemVersion,&version);
  713.     if(version>=0x605){            // Need new Palette Manager for reliable answer.
  714.         for(j=5;j>=0;j--)if(mode==HasDepth(device,1<<j,0,0))return 1<<j;
  715.     } else return 1<<(mode&7);    // Unreliable.
  716.     return 0;
  717. }
  718.  
  719. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr);
  720.  
  721. Boolean GDHasMode(GDHandle device,short mode,short *pixelSizePtr,short *pagesPtr)
  722. // Returns 0 if no such mode, returns 1 if mode is available.
  723. // If pixelSizePtr is not NULL, then sets *pixelSizePtr to pixelSize or -1 if unknown.
  724. // If pagesPtr is not NULL, then sets *pagesPtr to pages.
  725. {
  726.     short pixelSize,i,hasDepthWorks,pages;
  727.     int error;
  728.     long system;
  729.     
  730.     Gestalt(gestaltSystemVersion,&system);
  731.     // On Mac IIci, Sys 6.07, HasDepth returns "mode" of 0x100 at all legal depths.
  732.     hasDepthWorks= system>=0x605     // New Palette Manager.
  733.         && HasDepth(device,(**(**device).gdPMap).pixelSize,0,0)==(**device).gdMode;
  734.     if(hasDepthWorks){
  735.         for(i=0;i<6;i++){
  736.             pixelSize=1<<i;
  737.             if(mode!=HasDepth(device,pixelSize,0,0))continue;
  738.             if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  739.             if(pagesPtr!=NULL){
  740.                 error=GDGetPageCnt(device,mode,&pages);
  741.                 if(error)pages=1;
  742.                 *pagesPtr=pages;
  743.             }
  744.             return 1;
  745.         }
  746.         return 0;
  747.     }else{
  748.         // If HasDepth doesn't work properly then we can still find out whether the
  749.         // mode is available by asking the video driver for a page count, but
  750.         // I don't know of any discreet way to find out the pixelSize.
  751.         // Calling SetDepth would work, but that would irritate the user who has to
  752.         // watch and wait. 
  753.         error=GDGetPageCnt(device,mode,&pages);
  754.         if(error)pages=0;
  755.         if(pagesPtr!=NULL)*pagesPtr=pages;
  756.         if(mode==(**device).gdMode)pixelSize=(**(**device).gdPMap).pixelSize;
  757.         else pixelSize=-1;        // Unknown.
  758.         if(pixelSizePtr!=NULL)*pixelSizePtr=pixelSize;
  759.         return (pages>0);
  760.     }
  761. }
  762.  
  763. short gdClutSizeTable[33]={0,1<<1,1<<2,0,1<<4,0,0,0,1<<8,0,0,0,0,0,0,0,1<<5
  764. ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1<<8};
  765.  
  766. long GDColors(GDHandle device)
  767. // Returns the number of colors, in the current mode.
  768. {
  769.     long colors=0;
  770.     short pixelSize;
  771.     
  772.     if(device==NULL)return 2;    // for compatibility with 1-bit QuickDraw
  773.     pixelSize=(**(**device).gdPMap).pixelSize;
  774.     if(pixelSize>=1 && pixelSize<=8)colors=1<<pixelSize;
  775.     if(pixelSize==16)colors=1L<<15;
  776.     if(pixelSize==32)colors=1L<<24;
  777.     return colors;
  778. }
  779.  
  780. short GDClutSize(GDHandle device)
  781. // Returns the number of entries in the clut, in the current mode.
  782. {
  783.     short clutSize;
  784.     
  785.     // Method 1. Estimate clut size from pixel size.
  786.     clutSize=gdClutSizeTable[(**(**device).gdPMap).pixelSize];
  787.  
  788.     #if 0
  789.     // Method 2. Measure the clut's size by trying to load it.
  790.     if(GDType(device)==directType){
  791.         int error,i;
  792.         static const ColorSpec white={255,0xffff,0xffff,0xffff},black={0,0,0,0};
  793.         ColorSpec *table;
  794.         for(clutSize=256;clutSize>1;clutSize>>=1){
  795.             table=GDNewLinearColorTable(device);
  796.             if(table==NULL)PrintfExit("GDClutSize: out of memory.\n");
  797.             error=GDDirectSetEntries(device,0,clutSize-1,table);
  798.             DisposePtr((Ptr)table);
  799.             if(!error)break;
  800.         }
  801.     }
  802.     #endif
  803.     
  804.     return clutSize;
  805. }
  806.  
  807. short GDDacSize(GDHandle device)
  808. // Figures out how many bits in the video dac. Answers for each device are cached.
  809. {
  810.     short dacSize,i;
  811.     static short dacSizeCache[MAX_SCREENS];
  812.     static GDHandle deviceCache[MAX_SCREENS];
  813.     int error;
  814.     GammaTbl *gammaTblPtr=NULL;
  815.  
  816.     for(i=0;i<MAX_SCREENS;i++)if(device==deviceCache[i])return dacSizeCache[i];
  817.     error=GDGetGamma(device,&gammaTblPtr);        // Takes 200 µs.
  818.     if(error || gammaTblPtr==NULL || gammaTblPtr->gDataWidth==0)dacSize=8;                            // Oops. Take a guess.
  819.     else dacSize=gammaTblPtr->gDataWidth;
  820.     for(i=0;i<MAX_SCREENS;i++)if(NULL==deviceCache[i]){
  821.         deviceCache[i]=device;
  822.         dacSizeCache[i]=dacSize;
  823.         break;
  824.     }
  825.     return dacSize;
  826. }
  827.  
  828. ColorSpec *GDNewLinearColorTable(GDHandle device)
  829. // Creates a default table for use when gdType==directType.
  830. {
  831.     short clutSize,i;
  832.     ColorSpec *table,*linearTable;
  833.     
  834.     clutSize=GDClutSize(device);
  835.     table=linearTable=(ColorSpec *)NewPtr(clutSize*sizeof(linearTable[0]));
  836.     if(linearTable!=NULL)for(i=0;i<clutSize;i++){
  837.         table->rgb.red=table->rgb.green=table->rgb.blue
  838.             =(0xffffL*i+clutSize/2)/(clutSize-1);
  839.         table++;
  840.     }
  841.     return linearTable;
  842. }
  843.  
  844. /*
  845. Nominally equivalent to Apple's RestoreDeviceClut(), which is only available
  846. since System 6.05. However, I find that Apple's routine sometimes does nothing,
  847. whereas this routine always works. Passing a NULL argument causes restoration of
  848. cluts of all video devices.
  849. */
  850. OSErr GDRestoreDeviceClut(GDHandle device)
  851. {
  852.     int error,lastError;
  853.  
  854.     // If NULL, then call ourselves for each device.
  855.     if(device==NULL){
  856.         lastError=0;
  857.         device=GetDeviceList();
  858.         while(device!=NULL) {
  859.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  860.                 error=GDRestoreDeviceClut(device);
  861.                 if(error)lastError=error;
  862.             }
  863.             device=GetNextDevice(device);
  864.         }
  865.         return lastError;
  866.     }
  867.     if(GDType(device)!=directType){
  868.         error=GDSetEntries(device,0,(**(**(**device).gdPMap).pmTable).ctSize
  869.             ,((**(**(**device).gdPMap).pmTable)).ctTable);
  870.     }else error=GDSetGamma(device,NULL);
  871.     return error;
  872. }
  873.  
  874. GammaTbl **savedGammaTable[MAX_SCREENS];
  875.  
  876. OSErr GDSaveGamma(GDHandle device)
  877. {
  878.     GammaTbl *gamma;
  879.     int error,lastError;
  880.     long size;
  881.     int i;
  882.  
  883.     // If NULL, then call ourselves for each device.
  884.     if(device==NULL){
  885.         lastError=0;
  886.         device=GetDeviceList();
  887.         while(device!=NULL) {
  888.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  889.                 error=GDSaveGamma(device);
  890.                 if(error)lastError=error;
  891.             }
  892.             device=GetNextDevice(device);
  893.         }
  894.         return lastError;
  895.     }
  896.     if(device==NULL || (*device)->gdType==fixedType)return 0;
  897.     i=GetScreenIndex(device);
  898.     if(i>=MAX_SCREENS)return 1;
  899.     if(savedGammaTable[i]!=NULL)return 0;
  900.      error=GDGetGamma(device,&gamma);
  901.     if(error)return error;
  902.     size=gamma->gChanCnt*gamma->gDataCnt;
  903.     if(gamma->gDataWidth>8)size*=2;
  904.     size+=sizeof(GammaTbl)+gamma->gFormulaSize;
  905.     error=PtrToHand(gamma,(Handle *)&savedGammaTable[i],size);
  906.     return error;
  907. }
  908.  
  909. OSErr GDRestoreGamma(GDHandle device)
  910. {
  911.     int i,error,lastError;
  912.     
  913.     // If NULL, then call ourselves for each device.
  914.     if(device==NULL){
  915.         lastError=0;
  916.         device=GetDeviceList();
  917.         while(device!=NULL) {
  918.             if(TestDeviceAttribute(device,screenDevice) && TestDeviceAttribute(device,screenActive)){
  919.                 error=GDRestoreGamma(device);
  920.                 if(error)lastError=error;
  921.             }
  922.             device=GetNextDevice(device);
  923.         }
  924.         return lastError;
  925.     }
  926.     if((*device)->gdType==fixedType)return 0;
  927.     i=GetScreenIndex(device);
  928.     if(i>=MAX_SCREENS || savedGammaTable[i]==NULL)return 1;
  929.     error=GDSetGamma(device,*savedGammaTable[i]);
  930.     if(error)return error;
  931.     if(0){
  932.         DisposeHandle((Handle)savedGammaTable[i]);
  933.         savedGammaTable[i]=NULL;
  934.     }
  935.     return 0;
  936. }    
  937.  
  938. OSErr GDGetDefaultGamma(GDHandle device,GammaTbl **gammaTbl)
  939. // Looks for a default gamma table in both places that Apple says to look,
  940. // but usually comes up empty handed.
  941. {
  942.     int error,i,slot;
  943.     Scrn **scrn;
  944.     GammaTbl **gammaHandle,*gamma;
  945.     SpBlock spBlock;
  946.     Ptr ptr;
  947.  
  948.     gammaHandle=NULL;
  949.     if(CountResources('gama')>0){// Any 'gama' resources available in System file?
  950.         // Check to see if 'scrn' resource in System file specifies a 'gama' resource.
  951.         scrn=GDGetScrn(device);
  952.         if(scrn!=NULL && (**scrn).gammaTable!=-1)
  953.             gammaHandle=(GammaTbl **)GetResource('gama',(**scrn).gammaTable);
  954.         DisposeHandle((Handle)scrn);
  955.     }
  956.     if(gammaHandle!=NULL){
  957.         // Got gamma table from 'gama' resource.
  958.         gamma=(GammaTbl *)NewPtr(GetHandleSize((Handle)gammaHandle));
  959.         if(gamma==NULL)return MemError();
  960.         BlockMove(*gammaHandle,gamma,GetHandleSize((Handle)gammaHandle));
  961.         DisposeHandle((Handle)gammaHandle);
  962.     }else{
  963.         // Try to get this device's default gamma table from Slot Manager.
  964.         spBlock.spSlot=slot=GetDeviceSlot(device);
  965.         spBlock.spID=0;
  966.         spBlock.spExtDev=0;
  967.         spBlock.spTBMask=3;            // match only spCategory and spCType
  968.         spBlock.spCategory=catDisplay;
  969.         spBlock.spCType=typeVideo;    // this might be too restrictive, excludes LCD
  970.         do{
  971.             error=SNextTypeSRsrc(&spBlock);
  972.             if(error)return error;
  973.         }while(spBlock.spSlot!=slot || spBlock.spRefNum!=(**device).gdRefNum);
  974.         
  975.         if(0){
  976.             // Print sResource name
  977.             spBlock.spID=sRsrcName;
  978.             error=SGetCString(&spBlock);
  979.             printf("Slot resource \"%s\"\n",spBlock.spResult);
  980.             if(error)return error;
  981.             DisposePtr((Ptr)spBlock.spResult);
  982.         }
  983.         
  984.         // Look for gamma directory. Unfortunately many video devices don't have one.
  985.         spBlock.spID=sGammaDir;
  986.         error=SFindStruct(&spBlock);
  987.         if(error)return error;
  988.         
  989.         // Retrieve default gamma table
  990.         spBlock.spID=0x80;
  991.         error=SGetBlock(&spBlock);
  992.         if(error)return error;
  993.         gamma=(GammaTbl *)spBlock.spResult;
  994.         ptr=(Ptr)spBlock.spResult+6;
  995.         if(0)printf("Gamma table \"%s\", %ld bytes\n",ptr,GetPtrSize((Ptr)gamma));
  996.         ptr+=strlen(ptr)+1;                // table is just past string
  997.         ptr=(Ptr)((long)(ptr+1)&~1L);    // round up to even address
  998.         i=ptr-(Ptr)gamma;
  999.         BlockMove(ptr,(Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  1000.         SetPtrSize((Ptr)gamma,GetPtrSize((Ptr)gamma)-i);
  1001.     }
  1002.     *gammaTbl=gamma;
  1003.     return 0;
  1004. }
  1005.  
  1006. Scrn **GDGetScrn(GDHandle device)
  1007. // Returns handle to a copy of the specific scrn resource for this device,
  1008. // or NULL if none.
  1009. {
  1010.     int error=0,i,j;
  1011.     Scrns **scrns;
  1012.     Scrn *scrn,**scrnHandle;
  1013.     ScrnCtl *ctl;
  1014.     int scrnCount;
  1015.     long size;
  1016.  
  1017.     scrns=(Scrns **)GetResource('scrn',0);
  1018.     if(ResError())return NULL;
  1019.     HLockHi((Handle)scrns);
  1020.     scrnCount=(**scrns).scrnCount;
  1021.     scrn=&(**scrns).scrn;
  1022.     for(i=0;i<scrnCount;i++){
  1023.         if(0 && scrn->slot==GetDeviceSlot(device)){
  1024.             printf("Slot %d,",(int)scrn->slot);
  1025.             printf("mode %d,",(int)scrn->mode);
  1026.             printf("colorTable %d,",(int)scrn->colorTable);
  1027.             printf("gammaTable %d,",(int)scrn->gammaTable);
  1028.             printf("%d control calls:",(int)scrn->ctlCount);
  1029.         }
  1030.         ctl=&scrn->ctl;
  1031.         for(j=0;j<scrn->ctlCount;j++){
  1032.             if(0 && scrn->slot==GetDeviceSlot(device))printf(" %d",(int)ctl->csCode);
  1033.             ctl=(ScrnCtl *)((long)(ctl+1)+ctl->length);
  1034.         }
  1035.         if(0 && scrn->slot==GetDeviceSlot(device))printf("\n");
  1036.         size=(long)ctl-(long)scrn;
  1037.         if(scrn->slot==GetDeviceSlot(device))break;
  1038.         scrn=(Scrn *)ctl;
  1039.     }
  1040.     if(i<scrnCount){
  1041.         if(error)return NULL;
  1042.         scrnHandle=(Scrn **)NewHandle(size);
  1043.         BlockMove(scrn,*scrnHandle,size);
  1044.     }else scrnHandle=NULL;
  1045.     ReleaseResource((Handle)scrns);
  1046.     return scrnHandle;
  1047. }
  1048.  
  1049. OSErr GDUncorrectedGamma(GDHandle device)
  1050. /*
  1051. Loads a linear gamma table into the specified video device, to defeat the
  1052. driver's attempt to do gamma correction.
  1053.  
  1054. According to Designing Cards and Drivers, 3rd edition, passing a NULL
  1055. GammaTblPtr instructs the driver to create a linear table. 
  1056.  
  1057. */
  1058. {
  1059.     int error,i;
  1060.     GammaTbl *gamma=NULL;
  1061.     char *gData;
  1062.  
  1063.     if(0){
  1064.         /*
  1065.         The the following code first examines the current
  1066.         gamma table, and, if it's a plain vanilla table, as described in Designing Cards
  1067.         and Drivers, then we write-in the desired linear table. If it's fancy (or if the
  1068.         driver doesn't support GDGetGamma) then we pass a NULL pointer, letting the driver
  1069.         create the new table. Hopefully this will work with all drivers.
  1070.         */
  1071.         error=GDGetGamma(device,&gamma);
  1072.         if(!error && gamma->gVersion==0 && gamma->gChanCnt==1 && gamma->gDataWidth<=8){
  1073.             // Overwrite the standard table
  1074.             gData = (char *)&gamma->gFormulaData+gamma->gFormulaSize;
  1075.             for(i=0;i<gamma->gDataCnt;i++)gData[i]=i;
  1076.         }else{
  1077.             // A fancy table implies a new driver, so let it do the work.
  1078.             gamma=NULL;
  1079.         }
  1080.     }
  1081.     error=GDSetGamma(device,gamma);
  1082.     return error;
  1083. }
  1084.  
  1085. /* KillIO doesn't do anything, so I didn't bother to implement it. */
  1086.  
  1087. OSErr GDPrintGammaTable(FILE *o,GDHandle device)
  1088. {
  1089.     unsigned char *byte;
  1090.     unsigned short *word;
  1091.     int error,i,j,identity;
  1092.     GammaTbl *gamma;
  1093.     
  1094.     if((**device).gdType==fixedType)return statusErr;
  1095.     error=GDGetGamma(device,&gamma);
  1096.     if(error){
  1097.         fprintf(o,"GetGamma: GDGetGamma() error %d\n",error);
  1098.         if(error==statusErr)
  1099.             fprintf(o,"The video driver doesn't support this call.\n");
  1100.         return error;
  1101.     }
  1102.     byte=(unsigned char *)gamma->gFormulaData+gamma->gFormulaSize;
  1103.     word=(unsigned short *)byte;
  1104.     identity=1;
  1105.     if(gamma->gDataWidth<=8)
  1106.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==byte[i]);
  1107.     else
  1108.         for(i=0;i<gamma->gDataCnt;i++)identity &= (i==word[i]);
  1109.     if(identity){
  1110.         fprintf(o,"Gamma Table: identity transformation\n");
  1111.     }else{
  1112.         fprintf(o,"Gamma Table:\n");
  1113.         fprintf(o,"at 0x%lx,gDataWidth %d,gDataCnt %d,gVersion %d,gType %d,gFormulaSize %d,gChanCnt %d\n"
  1114.             ,gamma,(int)gamma->gDataWidth,(int)gamma->gDataCnt,(int)gamma->gVersion
  1115.             ,(int)gamma->gType,(int)gamma->gFormulaSize,(int)gamma->gChanCnt);
  1116.         for(i=0;i<gamma->gDataCnt;i+=64) {
  1117.             fprintf(o,"%3d: ",i);
  1118.             if(gamma->gDataWidth<=8)
  1119.                 for(j=0;j<16;j++) fprintf(o," %3u",byte[i+j]);
  1120.             else
  1121.                 for(j=0;j<16;j++) fprintf(o," %3u",word[i+j]);
  1122.             fprintf(o,"\n");
  1123.         }
  1124.     }
  1125.     return 0;
  1126. }
  1127.  
  1128. OSErr GDReset(GDHandle device, short *modePtr, short *pagePtr, Ptr *baseAddrPtr)
  1129. /*
  1130. Initialize the video card to its startup state, usually 1 bit per pixel. Returns
  1131. the parameters of that state.
  1132. */
  1133. {
  1134.     VDPageInfo myVDPageInfo;
  1135.     int error;
  1136.  
  1137.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1138.     myVDPageInfo.csMode= *modePtr;
  1139.     myVDPageInfo.csPage= *pagePtr;
  1140.     error=GDControl((*device)->gdRefNum,cscReset,(Ptr) &myVDPageInfo);
  1141.     *modePtr=myVDPageInfo.csMode;
  1142.     *pagePtr=myVDPageInfo.csPage;
  1143.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1144.     return error;
  1145. }
  1146.  
  1147. OSErr GDSetMode(GDHandle device,short mode,short page,Ptr *baseAddrPtr)
  1148. {
  1149.     VDPageInfo myVDPageInfo;
  1150.     int error;
  1151.  
  1152.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1153.     myVDPageInfo.csMode=mode;
  1154.     myVDPageInfo.csPage=page;
  1155.     error=GDControl((*device)->gdRefNum,cscSetMode,(Ptr) &myVDPageInfo);
  1156.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1157.     return error;
  1158. }
  1159.  
  1160. OSErr GDSwitchMode(GDHandle device,short mode,long displayModeID,short page,Ptr *baseAddrPtr);
  1161.  
  1162. OSErr GDSwitchMode(GDHandle device,short mode,long displayModeID,short page,Ptr *baseAddrPtr)
  1163. /* cscSwitchMode is documented in Designing PCI Video Cards and Drivers. */
  1164. {
  1165.     VDSwitchInfoRec vdSwitchInfo;
  1166.     int error;
  1167.  
  1168.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1169.     vdSwitchInfo.csMode=mode;
  1170.     vdSwitchInfo.csData=displayModeID;
  1171.     vdSwitchInfo.csPage=page;
  1172.     error=GDControl((*device)->gdRefNum,cscSwitchMode,(Ptr) &vdSwitchInfo);
  1173.     if(baseAddrPtr!=NULL) *baseAddrPtr=vdSwitchInfo.csBaseAddr;
  1174.     return error;
  1175. }
  1176.  
  1177. OSErr GDSetEntriesByType(GDHandle device,short start,short count,ColorSpec *table)
  1178. // Calls GDSetEntries or GDDirectSetEntries or nothing, as appropriate.
  1179. // Assumes that the GDevice record is valid, i.e. that the user has not
  1180. // called GDSetMode.
  1181. {
  1182.     switch((*device)->gdType){
  1183.     case fixedType:
  1184.         return statusErr;
  1185.     case clutType:
  1186.         return GDSetEntries(device,start,count,table);
  1187.     case directType:
  1188.         return GDDirectSetEntries(device,start,count,table);
  1189.     }
  1190.     return 1;
  1191. }
  1192.  
  1193. OSErr GDSetEntriesByTypeHighPriority(GDHandle device,short start,short count
  1194.     ,ColorSpec *table)
  1195. {
  1196.     char priority;
  1197.     int error;
  1198.  
  1199.     priority=7;
  1200.     SwapPriority(&priority);
  1201.     error=GDSetEntriesByType(device,start,count,table);
  1202.     SwapPriority(&priority);
  1203.     return error;
  1204. }
  1205.  
  1206. OSErr GDSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1207. {
  1208.     VDSetEntryRecord vDSetEntryRecord;
  1209.     int error;
  1210.  
  1211.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1212.     vDSetEntryRecord.csStart=start;
  1213.     vDSetEntryRecord.csCount=count;
  1214.     vDSetEntryRecord.csTable=table;
  1215.     error=GDControl((*device)->gdRefNum,cscSetEntries,(Ptr) &vDSetEntryRecord);
  1216.     return error;
  1217. }
  1218.  
  1219. OSErr GDSetGamma(GDHandle device, GammaTbl *gamma)
  1220. {
  1221.     int error;
  1222.     VDGammaRecord myVDGammaRecord;
  1223.  
  1224.     myVDGammaRecord.csGTable=(Ptr)gamma;
  1225.     error=GDControl((*device)->gdRefNum,cscSetGamma,(Ptr) &myVDGammaRecord);
  1226.     return error;
  1227. }
  1228.  
  1229. OSErr GDGrayPage(GDHandle device,short page)
  1230. /*
  1231. Called "GrayScreen" in Designing Cards and Drivers, 3rd Ed. Fills the specified
  1232. page with gray, i.e. the dithered desktop pattern. I'm not aware of any
  1233. particular advantage in using this instead of FillRect().
  1234.  
  1235. Designing Cards and Drivers, 3rd Edition, Chapter 9, says that for direct
  1236. devices, i.e. >8 bit pixels, the driver will also load a linear,
  1237. gamma-corrected, gray color table.
  1238.  
  1239. Contrary to the documentation, version 2 (in System 6.03) of the video driver
  1240. for Apple's old video card requires that one supply the current mode as well.
  1241. Supplying a garbage mode screwed up the screen and soon hung the software. So
  1242. this code first obtains the current mode, and then supplies it in the GrayPage
  1243. Control call.
  1244. */
  1245. {
  1246.     VDPageInfo myVDPageInfo;
  1247.     int error;
  1248.     /* The rest of the arguments are used soley for the bug fix */
  1249.     short mode=0;        /* should be ignored, but isn't */
  1250.     short actualPage;    /* ignored */
  1251.     Ptr baseAddr;        /* ignored */
  1252.  
  1253.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1254.     
  1255.     /* Work around driver bug: get the mode */
  1256.     error=GDGetMode(device,&mode,&actualPage,&baseAddr);
  1257.     if(error)return error;
  1258.     myVDPageInfo.csMode=mode;
  1259.     
  1260.     myVDPageInfo.csPage=page;
  1261.     error=GDControl((*device)->gdRefNum,cscGrayPage,(Ptr) &myVDPageInfo);
  1262.     return error;
  1263. }
  1264.  
  1265. OSErr GDSetGray(GDHandle device,Boolean flag)
  1266. /*
  1267. Tells the driver whether you want colors (flag==0), or prefer that all colors be 
  1268. mapped to luminance-equivalent gray tones? (flag==1).
  1269. */
  1270. {
  1271.     VDFlagRec myVDFlagRec;
  1272.     int error;
  1273.  
  1274.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1275.     myVDFlagRec.flag=flag;
  1276.     error=GDControl((*device)->gdRefNum,cscSetGray,(Ptr) &myVDFlagRec);
  1277.     return error;
  1278. }
  1279.  
  1280. OSErr GDSetInterrupt(GDHandle device,Boolean flag)
  1281. /*
  1282. Set flag to 1 to enable VBL interrupts of this card, or 0 to disable. 
  1283. I don't know when it's appropriate to call this.
  1284. */
  1285. {
  1286.     VDFlagRec myVDFlagRec;
  1287.     int error;
  1288.  
  1289.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1290.     myVDFlagRec.flag=flag;
  1291.     error=GDControl((*device)->gdRefNum,cscSetInterrupt,(Ptr) &myVDFlagRec);
  1292.     return error;
  1293. }
  1294.  
  1295. OSErr GDDirectSetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1296. /*
  1297. If your pixel depth is >8 then the cscSetEntries Control call is disabled, and you use
  1298. cscDirectSetEntries instead. Except for that, GDDirectSetEntries is identical to GDSetEntries.
  1299. */
  1300. {
  1301.     VDSetEntryRecord vDSetEntryRecord;
  1302.     int error;
  1303.  
  1304.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1305.     vDSetEntryRecord.csStart=start;
  1306.     vDSetEntryRecord.csCount=count;
  1307.     vDSetEntryRecord.csTable=table;
  1308.     error=GDControl((*device)->gdRefNum,cscDirectSetEntries,(Ptr) &vDSetEntryRecord);
  1309.     return error;
  1310. }
  1311.  
  1312. OSErr GDSetDefaultMode(GDHandle device,short mode)
  1313. /*
  1314. Supposedly, you tell it what mode you want to start up with when you reboot.
  1315. (I've never been able to get this to work. No error and no effect. Perhaps I've
  1316. misunderstood its purpose.)
  1317. */
  1318. {
  1319.     VDDefModeRec myVDDefModeRec;
  1320.     int error;
  1321.  
  1322.     if(device==NULL || (*device)->gdRefNum==0) return controlErr;
  1323.     myVDDefModeRec.spID=mode;
  1324.     error=GDControl((*device)->gdRefNum,cscSetDefaultMode,(Ptr) &myVDDefModeRec);
  1325.     return error;
  1326. }
  1327.  
  1328. OSErr GDGetMode(GDHandle device,short *modePtr,short *pagePtr,Ptr *baseAddrPtr)
  1329. /*
  1330. It tells you the current mode, page of video memory, and the base address of that
  1331. page.
  1332. */
  1333. {
  1334.     VDPageInfo myVDPageInfo;
  1335.     int error;
  1336.  
  1337.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1338.     error=GDStatus((*device)->gdRefNum,cscGetMode,(Ptr) &myVDPageInfo);
  1339.     if(modePtr!=NULL)*modePtr=myVDPageInfo.csMode;
  1340.     if(pagePtr!=NULL)*pagePtr=myVDPageInfo.csPage;
  1341.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1342.     return error;
  1343. }
  1344.  
  1345. OSErr GDGetEntries(GDHandle device,short start,short count,ColorSpec *table)
  1346. /*
  1347. This is much as you'd expect after reading GDSetEntries above. Note that unless
  1348. the gamma table is linear, the values returned may not be the same as those
  1349. originally passed by GDSetEntries. So call GDUncorrectedGamma first. Note that
  1350. version 2 (in System 6.03) of the video driver for Apple's old video card had a
  1351. bug and did not support "indexed" mode, i.e. start==-1. This is fixed in System
  1352. 6.05. Apple's .Display_Video_Apple_RBV1 v. 0 video driver (built-in to Mac IIci)
  1353. crashes if you attempt to make this call. However, that's a thing of the past,
  1354. because we now first patch the driver to fix the bug. Try the demo TimeVideo.
  1355. */
  1356. {
  1357.     VDSetEntryRecord vDSetEntryRecord;
  1358.     int error;
  1359.     static int bugsPatched=0;
  1360.     unsigned char *name;
  1361.     int version;
  1362.  
  1363.     if(device==NULL || (*device)->gdRefNum==0)return statusErr;
  1364.     if(!bugsPatched){
  1365.         PatchMacIIciVideoDriver();
  1366.         bugsPatched=1;
  1367.     }
  1368.  
  1369.     // Contrary to Apple's rules, these drivers crash if we attempt
  1370.     // a getEntries call. So let's be polite and instead simply return
  1371.     // an error message indicating that this call is not available.
  1372.     name=GDName(device);
  1373.     version=GDVersion(device);
  1374.     if(EqualString(name,"\p.Display_Video_Apple_RBV1",1,1) && version==0)return statusErr;
  1375.     if(EqualString(name,"\p.Color_Video_Display",1,1) && version==9288)return statusErr;
  1376.     if(EqualString(name,"\p.Display_Video_Apple_DOMEMax",1,1) && version==2)return statusErr;
  1377.     vDSetEntryRecord.csStart=start;
  1378.     vDSetEntryRecord.csCount=count;
  1379.     vDSetEntryRecord.csTable=table;
  1380.     error=GDStatus((*device)->gdRefNum,cscGetEntries,(Ptr) &vDSetEntryRecord);
  1381.     return error;
  1382. }
  1383.  
  1384. OSErr GDGetPageCnt(GDHandle device,short mode,short *pagesPtr)
  1385. /*
  1386. Called "GetPages" in Designing Cards and Drivers, 3rd Ed. You tell it what mode
  1387. you're interested in. It tells you how many pages of video ram are available.
  1388. */
  1389. {
  1390.     VDPageInfo myVDPageInfo;
  1391.     int error;
  1392.  
  1393.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1394.     myVDPageInfo.csMode=mode;
  1395.     error=GDStatus((*device)->gdRefNum,cscGetPageCnt,(Ptr) &myVDPageInfo);
  1396.     if(!error)*pagesPtr=myVDPageInfo.csPage;
  1397.     return error;
  1398. }
  1399.  
  1400. OSErr GDGetPageBase(GDHandle device,short page,Ptr *baseAddrPtr)
  1401. /*
  1402. Called "GetBaseAddr" in Designing Cards and Drivers, 3rd Ed. You tell it what
  1403. page of video memory you're interested in (in the current video mode). It tells
  1404. you the base address of that page.
  1405. */
  1406. {
  1407.     VDPageInfo myVDPageInfo;
  1408.     int error;
  1409.  
  1410.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1411.     myVDPageInfo.csPage=page;
  1412.     error=GDStatus((*device)->gdRefNum,cscGetPageBase,(Ptr) &myVDPageInfo);
  1413.     if(baseAddrPtr!=NULL) *baseAddrPtr=myVDPageInfo.csBaseAddr;
  1414.     return error;
  1415. }
  1416.  
  1417. OSErr GDGetGray(GDHandle device,Boolean *flagPtr)
  1418. // It tells you what the flag is set to. Do you want colors? (flag==0) Or do you
  1419. // want all colors mapped to luminance-equivalent gray tones? (flag==1).
  1420. {
  1421.     VDFlagRec myVDFlagRec;
  1422.     int error;
  1423.  
  1424.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1425.     error=GDStatus((*device)->gdRefNum,cscGetGray,(Ptr) &myVDFlagRec);
  1426.     *flagPtr=myVDFlagRec.flag;
  1427.     return error;
  1428. }
  1429.  
  1430. OSErr GDGetInterrupt(GDHandle device,Boolean *flagPtr)
  1431. // Get flag. 1 if VBL interrupts of this card are enabled. 0 if disabled. 
  1432. {
  1433.     VDFlagRec myVDFlagRec;
  1434.     int error;
  1435.  
  1436.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1437.     error=GDStatus((*device)->gdRefNum,cscGetInterrupt,(Ptr) &myVDFlagRec);
  1438.     *flagPtr=myVDFlagRec.flag;
  1439.     return error;
  1440. }
  1441.  
  1442. OSErr GDGetGamma(GDHandle device,GammaTbl **myGammaTblHandle)
  1443. /*
  1444. Returns a pointer to the Gamma table in the specified video device. (I.e. you
  1445. pass it a pointer to your pointer, a handle, which it uses to load your
  1446. pointer.)
  1447.  
  1448. Note that version 2 (in System ≤6.03) of the video driver for Apple's old video
  1449. card does not support this call due to a bug in the driver code. The later
  1450. versions of the driver (3, 4, and 5, in System 6.04 and later) work correctly.
  1451. */
  1452. {
  1453.     int error;
  1454.     VDGammaRecord myVDGammaRecord;
  1455.  
  1456.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1457.     myVDGammaRecord.csGTable=NULL;    // default address is NULL
  1458.     error=GDStatus((*device)->gdRefNum,cscGetGamma,(Ptr) &myVDGammaRecord);
  1459.     *myGammaTblHandle=(GammaTblPtr)myVDGammaRecord.csGTable;
  1460.     return error;
  1461. }
  1462.  
  1463. OSErr GDGetDefaultMode(GDHandle device,short *modePtr)
  1464. // It tells you what the default mode is. I'm not sure what this means.
  1465. {
  1466.     VDDefModeRec myVDDefModeRec;
  1467.     int error;
  1468.  
  1469.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1470.     error=GDStatus((*device)->gdRefNum,cscGetDefaultMode,(Ptr) &myVDDefModeRec);
  1471.     *modePtr=(unsigned char)myVDDefModeRec.spID;
  1472.     return error;
  1473. }
  1474.  
  1475. OSErr GDControl(int refNum,int csCode,Ptr csParamPtr)
  1476. // Uses low-level PBControl() call to implement a "Control()" call that works! 
  1477. // I don't know why this wasn't discussed in Apple Tech Note 262.
  1478. {
  1479.     CntrlParam control;
  1480.     int error;
  1481.     
  1482.     control.ioCompletion=NULL;
  1483.     control.ioCRefNum=refNum;
  1484.     control.csCode=csCode;
  1485.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1486.     error=PBControl((ParmBlkPtr) &control,0);
  1487.     return error;
  1488. }
  1489.  
  1490. OSErr GDStatus(int refNum,int csCode,Ptr csParamPtr)
  1491. // Uses low-level PBStatus() call to implement a "Status()" call that works! The
  1492. // need for this is explained in Apple Tech Note 262, which was issued in response
  1493. // to my bug report in summer of '89.
  1494. {
  1495.     CntrlParam control;
  1496.     int error;
  1497.     
  1498.     control.ioCompletion=NULL;
  1499.     control.ioCRefNum=refNum;
  1500.     control.csCode=csCode;
  1501.     *((Ptr *) &control.csParam[0]) = csParamPtr;
  1502.     error=PBStatus((ParmBlkPtr) &control,0);
  1503.     return error;
  1504. }
  1505.  
  1506. #if 0
  1507. /*
  1508. From: absurd@apple.apple.com (Tim Dierks, software saboteur)
  1509. Date: Fri, 20 Nov 1992 00:38:14 GMT
  1510. Organization: MacDTS Marauders
  1511.  
  1512. Here's the right way to get the slot number of a monitor, given its
  1513. GDevice:  (as a bonus, this also gets the name of the card in
  1514. question; to just get the slot, chop off all the lines after the
  1515. *slot = ... line.
  1516.  
  1517. 10/4/95 dgp added safety checks at beginning to make sure device handle is
  1518. not NULL and that the Slot Manager is present (e.g. a PCI machine).
  1519. */
  1520.  
  1521. OSErr GetSlotAndName(GDHandle device,short *slot,char *name)
  1522. {   OSErr error;
  1523.     SpBlock spBlock;
  1524.     Boolean slotMgrPresent;
  1525.     
  1526.     slot=-1;
  1527.     name[0]=0;
  1528.     if(TrapAvailable(_SlotManager))slotMgrPresent=(SVersion(&spBlock)==noErr);
  1529.     else slotMgrPresent=0;
  1530.     if(!slotMgrPresent || device==NULL || (*device)->gdRefNum==0)return -1;
  1531.     *slot = (**(AuxDCEHandle)GetDCtlEntry((**device).gdRefNum)).dCtlSlot;
  1532.     spBlock.spSlot = *slot;         // In the slot we're interested in
  1533.     spBlock.spID = 0;
  1534.     spBlock.spExtDev = 0;
  1535.     spBlock.spCategory = 1;         // Get the board sResource
  1536.     spBlock.spCType = 0;
  1537.     spBlock.spDrvrSW = 0;
  1538.     spBlock.spDrvrHW = 0;
  1539.     spBlock.spTBMask = 0;
  1540.     error = SNextTypeSRsrc(&spBlock);
  1541.     if(error)return error;
  1542.     spBlock.spID = 2;               // Getting the description string
  1543.                                     // spSPointer was set up by SNextTypesResource
  1544.     error = SGetCString(&spBlock);
  1545.     if(error)return error;
  1546.     strcpy(name,(char *)spBlock.spResult);  // Get the returned string
  1547.     DisposePtr((Ptr)spBlock.spResult);    // Undocumented; we have to dispose of it
  1548.     c2pstr(name);
  1549.     return noErr;
  1550. }
  1551. #endif
  1552.  
  1553. char *GDCardName(GDHandle device)
  1554. /*
  1555. Returns the address of a C string containing the name of the video card. You
  1556. should call DisposPtr() on the returned address when you no longer need it.
  1557. Takes about 1.5 ms; I don't know why Apple's slot routines are so slow. This
  1558. routine sets up the flags in the SNextTypeSRsrc() call quite differently from
  1559. the above example, but I don't know if that matters, since I've been using this
  1560. routine for a year or so without any problems.
  1561.  
  1562. Now works for PCI video devices as well.
  1563. */
  1564. {
  1565.     AuxDCE **auxDCEHandle;
  1566.     SpBlock spBlock,spBlock1;
  1567.     Boolean slotMgrPresent;
  1568.     char slotName[32],cardName[32],modelName[32];
  1569.     
  1570.     GetVideoProperties(device,slotName,cardName,modelName);    /* in UseNameRegistry.c */
  1571.     if(strlen(cardName)>0){
  1572.         Ptr p;
  1573.         if(strlen(slotName)==0)strcpy(cardName,"Built-in video");
  1574.         p=NewPtr(strlen(cardName)+1);
  1575.         strcpy(p,cardName);
  1576.         return p;
  1577.     }
  1578.     if(TrapAvailable(_SlotManager))slotMgrPresent=(SVersion(&spBlock)==noErr);
  1579.     else slotMgrPresent=0;
  1580.     if(!slotMgrPresent || device==NULL || (*device)->gdRefNum==0){
  1581.         Ptr p;
  1582.         p=NewPtr(1);
  1583.         p[0]=0;
  1584.         return p;
  1585.     }
  1586.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1587.     spBlock.spSlot = (**auxDCEHandle).dCtlSlot;
  1588.     spBlock.spCategory = 0;
  1589.     spBlock.spCType =     0;
  1590.     spBlock.spDrvrSW =     0;
  1591.     spBlock.spDrvrHW =     1;
  1592.     spBlock.spTBMask = 0xf;
  1593.     spBlock.spID = 0;
  1594.     spBlock.spExtDev = 0;
  1595.     if(SNextTypeSRsrc(&spBlock) == noErr) {
  1596.         spBlock1.spsPointer = spBlock.spsPointer;
  1597.         spBlock1.spID = 2;
  1598.         SGetCString(&spBlock1);
  1599.         return (char *)spBlock1.spResult;
  1600.     }
  1601.     else{
  1602.         Ptr p;
  1603.         p=NewPtr(1);
  1604.         p[0]=0;
  1605.         return p;
  1606.     }
  1607. }
  1608.  
  1609. #if 0
  1610.     flags The flags word in the driver’s DCE.
  1611.     
  1612.     
  1613.     //#include <NameRegistry.h>
  1614.     //#include <Drivers.h>
  1615. #endif
  1616.  
  1617. OSErr GDGestalt(GDHandle device,OSType driverGestaltSelector,unsigned long *driverGestaltResponsePtr)
  1618. {
  1619.     int error;
  1620.  
  1621.     if(device==NULL || (*device)->gdRefNum==0) return statusErr;
  1622.     error=DriverGestalt((*device)->gdRefNum,driverGestaltSelector,driverGestaltResponsePtr);
  1623.     return error;
  1624. }
  1625.  
  1626. struct DriverGestaltParam {
  1627.     QElemPtr qLink;
  1628.     short qType;
  1629.     short ioTrap;
  1630.     Ptr ioCmdAddr;
  1631.     ProcPtr ioCompletion;
  1632.     OSErr ioResult;
  1633.     StringPtr ioNamePtr;
  1634.     short ioVRefNum;
  1635.     short ioCRefNum; /* refNum for I/O operation*/
  1636.     short csCode; /* == driverGestaltCode */
  1637.     OSType driverGestaltSelector;
  1638.     unsigned long driverGestaltResponse;
  1639. };
  1640. typedef struct DriverGestaltParam DriverGestaltParam;
  1641. enum{kcsDriverGestalt=43};
  1642. enum{kmDriverGestaltEnableMask=1L<<2};
  1643.  
  1644. Boolean GDGestaltIsOn(GDHandle device)
  1645. {
  1646.     AuxDCE **auxDCEHandle;
  1647.  
  1648.     if(device==NULL || (*device)->gdRefNum==0) return 0;
  1649.     auxDCEHandle=(AuxDCE **)GetDCtlEntry((*device)->gdRefNum);
  1650.     return (**auxDCEHandle).dCtlFlags & kmDriverGestaltEnableMask;
  1651. }
  1652.  
  1653. OSErr DriverGestalt(int refNum,OSType driverGestaltSelector,unsigned long *driverGestaltResponsePtr)
  1654. /*
  1655. Implements Driver Gestalt, documented in Designing PCI Cards and Drivers
  1656. */
  1657. {
  1658.     DriverGestaltParam param;
  1659.     int error;
  1660.     AuxDCE **auxDCEHandle;
  1661.  
  1662.     auxDCEHandle=(AuxDCE **)GetDCtlEntry(refNum);
  1663.     if(!((**auxDCEHandle).dCtlFlags & kmDriverGestaltEnableMask))return statusErr;
  1664.     param.ioCompletion=NULL;
  1665.     param.ioCRefNum=refNum;
  1666.     param.csCode=kcsDriverGestalt;
  1667.     param.driverGestaltSelector=driverGestaltSelector;
  1668.     param.driverGestaltResponse=0;
  1669.     error=PBStatus((ParmBlkPtr) ¶m,0);
  1670.     if(driverGestaltResponsePtr!=NULL) *driverGestaltResponsePtr=param.driverGestaltResponse;
  1671.     return error;
  1672. }
  1673.  
  1674. #if 0
  1675.     struct DriverType {
  1676.         Str31 nameInfoStr;
  1677.         NumVersion version;
  1678.     }
  1679.     typedef UInt32 DeviceTypeMember;
  1680.     typedef struct DriverType DriverType;
  1681.     typedef struct DriverType *DriverTypePtr;
  1682.     struct DriverOSRuntime {
  1683.     RuntimeOptions driverRuntime;
  1684.     Str31 driverName;
  1685.     UInt32 driverDescReserved[8];
  1686.     };
  1687.     typedef OptionBits RuntimeOptions;
  1688.     typedef struct DriverOSRuntime DriverOSRuntime;
  1689.     
  1690.     struct DriverDescription {
  1691.         OSType driverDescSignature;
  1692.         DriverDescVersion driverDescVersion;
  1693.         DriverType driverType;
  1694.         DriverOSRuntime driverOSRuntimeInfo;
  1695.         DriverOSService driverServices;
  1696.     };
  1697.     typedef struct DriverDescription DriverDescription;
  1698.     typedef struct DriverDescription *DriverDescriptionPtr;
  1699.  
  1700.     OSErr GetDriverName(GDHandle device,unsigned char *name);
  1701.     
  1702.     OSErr GetDriverName(GDHandle device,unsigned char *name)
  1703.     {
  1704.         long nameRegistryVersion;
  1705.         OSErr error;
  1706.         UnitNumber unit;
  1707.         DriverFlags flags;
  1708.         FSSpec driverFileSpec;
  1709.         RegEntryID regEntryID;
  1710.         CFragHFSLocator loc;
  1711.         CFragConnectionID fragmentConnID;
  1712.         DriverOpenCount openCount;
  1713.         DriverEntryPointPtr fragmentMain;
  1714.         DriverDescription driverDescription;
  1715.     
  1716.         name[0]=0;
  1717.         error=Gestalt('nreg',&nameRegistryVersion);
  1718.         if(!error){
  1719.             loc.u.onDisk.fileSpec = &driverFileSpec;
  1720.             error=GetDriverInformation((*device)->gdRefNum,&unit,&flags,&openCount,name
  1721.                 ,®EntryID,&loc,&fragmentConnID,&fragmentMain,&driverDescription);
  1722.         }
  1723.         return error;
  1724.     }
  1725. #endif
  1726.  
  1727. unsigned char *GDName(GDHandle device)
  1728. // Returns a pointer to the name of the driver (a pascal string). 
  1729. {
  1730.     VideoDriver *videoDriverPtr;
  1731.  
  1732.     if(device==NULL || (*device)->gdRefNum==0)return "\p";
  1733.     videoDriverPtr=GDDriverAddress(device);
  1734.     return videoDriverPtr->name;
  1735. }
  1736.  
  1737. char *GDNameStr(GDHandle device)
  1738. // Returns the driver name as a C string.
  1739. {
  1740.     unsigned char *sp;
  1741.     static char name[32];
  1742.     
  1743.     sp=GDName(device);
  1744.     memcpy(name,sp,sp[0]+1);
  1745.     return p2cstr((unsigned char *)name);
  1746. }
  1747.  
  1748. int GDVersion(GDHandle device)
  1749. // Returns the version number of the driver. From the first word-aligned word after
  1750. // the name string.
  1751. {
  1752.     int version;
  1753.     unsigned char *bytePtr;
  1754.  
  1755.     if(device==NULL || (*device)->gdRefNum==0)return 0;
  1756.     bytePtr=GDName(device);
  1757.     bytePtr += 1+bytePtr[0];    /* go to end of Pascal string */
  1758.     bytePtr = (unsigned char *)((long)(bytePtr+1) & ~1);    // round up to word boundary
  1759.     version = *(short *)bytePtr;
  1760.     return version;
  1761. }
  1762.  
  1763. VideoDriver *GDDriverAddress(GDHandle device)
  1764. // Returns a pointer to the driver, whether in ROM or RAM. 
  1765. {
  1766.     AuxDCE **auxDCEHandle;
  1767.     VideoDriver *videoDriverPtr;
  1768.  
  1769.     if(device==NULL || (*device)->gdRefNum==0)return NULL;
  1770.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1771.     if((**auxDCEHandle).dCtlFlags & dRAMBasedMask){
  1772.         /* RAM-based driver. */
  1773.         videoDriverPtr=*(VideoDriver **) (**auxDCEHandle).dCtlDriver;
  1774.     }
  1775.     else{
  1776.         /* ROM-based driver. */
  1777.         videoDriverPtr=(VideoDriver *) (**auxDCEHandle).dCtlDriver;
  1778.     }
  1779.     return videoDriverPtr;
  1780. }
  1781.  
  1782. /*
  1783. ROUTINE: PatchMacIIciVideoDriver
  1784. PURPOSE:
  1785. It is unlikely that you will need to call this explicitly, because it is called
  1786. automatically by GDGetEntries the first time it is invoked, and the sole purpose
  1787. of this routine is to fix a driver bug that would cause a crash when called by
  1788. GDGetEntries.
  1789.  
  1790. The Mac IIci built-in video driver (.Display_Video_Apple_RBV1 driver, version 0)
  1791. has a bug that causes it to crash if you try to do a getEntries Status request.
  1792. PatchMacIIciVideoDriver() will find and patch the memory-resident copy of the
  1793. buggy driver. Only two instructions are modified, to save and restore more
  1794. registers. This fix persists only until the next reboot. If the patch is
  1795. successfully applied the version number is increased from 0 to 100, to
  1796. distinguish it from versions 0 and 1.
  1797.  
  1798. A returned value of 1 indicates success: the needed patch was applied, either now
  1799. or previously. A return value of 0 indicates no patch was needed.
  1800.  
  1801. This patch is based on a comparison of the version 0 and 1 drivers used by the
  1802. Mac IIci and IIsi, respectively. The patch changes a pair of save and restore
  1803. operations (MOVEM.L to and from the stack) to save and restore registers D1 and
  1804. A1 as well as D4, A3, and A4. There are many other differences between versions
  1805. 0 and 1 of the driver, but this change is enough to keep the version 0 driver
  1806. from crashing when we attempt to read the clut by calling GDGetEntries.
  1807.  
  1808. The only change that the Mac operating system could possibly notice is that,
  1809. when we're done patching, we set the handle to be non-purgeable, since purging
  1810. and reloading the driver would eliminate the patch.
  1811.  
  1812. edward_de_Jong@bmug.org and Robert Savoy (SAVOY@RISVAX.ROWLAND.ORG) reported
  1813. that their Mac IIci computers' built-in video driver is ROM-based, so
  1814. PatchMacIIciVideoDriver was enhanced to deal with a ROM-based driver, by copying
  1815. the driver into RAM, making that the active driver, and patching it. Robert
  1816. Savoy reports that it works fine.
  1817.  
  1818. An alternative, permanent, solution is described in the file "Video synch":
  1819. upgrading to Apple's bug-free version 1 of the driver. However, that solution
  1820. only works if the Mac IIci has more than one monitor.
  1821.  
  1822. */
  1823.  
  1824. int PatchMacIIciVideoDriver(void)
  1825. {
  1826.     GDHandle device;
  1827.     short *w;
  1828.     AuxDCE **auxDCEHandle;
  1829.     Handle handle;
  1830.     enum{badVersion=0};
  1831.     int error;
  1832.     long value;
  1833.     
  1834.     error=Gestalt(gestaltQuickdrawVersion,&value);
  1835.     if(error || value<gestalt8BitQD)return 0;    // need 8-bit quickdraw
  1836.     device = GetDeviceList();
  1837.     while(1) {
  1838.         if(device==NULL || (*device)->gdRefNum==0)return 0;
  1839.         if (!TestDeviceAttribute(device,screenDevice)
  1840.             || !TestDeviceAttribute(device,screenActive)){
  1841.             device=GetNextDevice(device);
  1842.             continue;
  1843.         }
  1844.         if(EqualString("\p.Display_Video_Apple_RBV1",GDName(device),1,1))
  1845.             switch(GDVersion(device)){
  1846.                 case badVersion:
  1847.                     break;
  1848.                 case badVersion+100:    // already patched
  1849.                     return 1;
  1850.                 default:
  1851.                     return 0;
  1852.         }else{
  1853.             device=GetNextDevice(device);
  1854.             continue;
  1855.         }
  1856.         break;
  1857.     }
  1858.     auxDCEHandle = (AuxDCE **) GetDCtlEntry((*device)->gdRefNum);
  1859.     
  1860.     // Move ROM-based driver into RAM.
  1861.     if(!((**auxDCEHandle).dCtlFlags & dRAMBasedMask)){
  1862.         long bytes;
  1863.         VideoDriver *driver;
  1864.         
  1865.         driver=(VideoDriver *)(**auxDCEHandle).dCtlDriver;
  1866.         // Sometimes the word preceding the driver in ROM seems to be the
  1867.         // driver size, but not always, e.g. the built-in driver on the Mac IIsi.
  1868.         bytes=*((short *)driver-1);
  1869.         // Driver size unknown, guessing (generously) at twice the highest offset.
  1870.         bytes=driver->open;
  1871.         if(bytes<driver->prime)bytes=driver->prime;
  1872.         if(bytes<driver->control)bytes=driver->control;
  1873.         if(bytes<driver->status)bytes=driver->status;
  1874.         if(bytes<driver->close)bytes=driver->close;
  1875.         bytes*=2;
  1876.         // We know the Mac IIci driver size to be 1896
  1877.         // when ROM version is 124 rev. 1, but who knows for later ROMs?
  1878.         //bytes=1896;
  1879.         handle=NewHandleSys(bytes);
  1880.         if(handle==NULL)return 0;    // Insufficient room on System heap.
  1881.         HLockHi(handle);
  1882.         BlockMove((Ptr)driver,*handle,bytes);
  1883.         (**auxDCEHandle).dCtlDriver=(Ptr)handle;
  1884.         (**auxDCEHandle).dCtlFlags |= dRAMBasedMask;        
  1885.     }
  1886.     
  1887.     // Patch RAM-based driver.
  1888.     handle=(Handle)(**auxDCEHandle).dCtlDriver;
  1889.     w=*(short **)handle;
  1890.     if(w[0x51e/2]!=0x818 || w[0x590/2]!=0x1810 || w[0x2c/2]!=badVersion){
  1891.         printf("PatchMacIIciVideoDriver error.\n");
  1892.         return 0;
  1893.     }
  1894.     w[0x51e/2]=0x4858;
  1895.     w[0x590/2]=0x1a12;
  1896.     w[0x2c/2]+=100;                                    // Change version number.
  1897.     if(w[0x51e/2]!=0x4858 || w[0x590/2]!=0x1a12){
  1898.         printf("PatchMacIIciVideoDriver error.\n");
  1899.         return 0;
  1900.     }
  1901.     HNoPurge(handle);
  1902.     return 1;
  1903. }
  1904.  
  1905. /*
  1906. Received:    10/24
  1907. From:        Fernando Urbina, nano@apple.com
  1908. To:          Denis Pelli, denis@cns.nyu.edu
  1909.  
  1910. The following is the information on the private call for the 7500 and the 
  1911. 8500 to disable waiting for VBL's and to change the time that we wait for 
  1912. the CLUT to settle after writing each entry in the CLUT.  As shipped, the 
  1913. driver waits for 800 nanoseconds after writing each RGB triplet, to allow 
  1914. the hardware to increment the CLUT address.
  1915.  
  1916. cscSetTimeDelays is used to set some flags and time delays used to write the
  1917. CLUT. Use PBControl to issue the call, with the csParam[0] containing a pointer
  1918. to a VDTimeDelay structure. Set the "validMask" field with the bits
  1919. indicating which parameters you want to set.
  1920.  
  1921. cscGetTimeDelays is used to examine the current values of the flags and time
  1922. delays. Use PBStatus instead of PBControl. Set the "validMask" field
  1923. with the bits indicating which parameters you want to get.
  1924.  
  1925. The following is the definition of the fields of the VDTimeDelay struct:
  1926.  
  1927. flags, bit 0:  DontWaitForVBL flag:  When false, it means that the driver should
  1928. wait for a VBL before writing the CLUT.  When true, the driver should NOT wait
  1929. for a VBL.
  1930.  
  1931. flags, bit 1:  SetCLUTAddrRegTiming flag:  When false, use the default timing.
  1932. When true, use paramOne and paramTwo to specify the delay in nanoseconds.
  1933.  
  1934. validMask: Specifies which bits in flags are valid.  Bits are valid when
  1935. corresponding bit position is 1.
  1936.  
  1937. paramOne,paramTwo: When the SetCLUTAddrRegTiming bit of the validMask is set,
  1938. then these fields specify the delay, in nanoseconds: nanoseconds.hi in paramOne
  1939. and nanoseconds.lo in paramTwo.  See Designing PCI Cards & Drivers for the
  1940. Nanoseconds data structure.
  1941.  
  1942. */
  1943. enum{cscSetTimeDelays = 141};    // Used to set the different time delays
  1944. enum{cscGetTimeDelays = 141};
  1945. enum{gDontWaitForVBLMask=1,gSetCLUTTimingMask=2};
  1946. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  1947.     #pragma options align=mac68k
  1948. #endif
  1949. struct VDTimeDelays{
  1950.     UInt32 flags;
  1951.     UInt32 validMask;
  1952.     UInt32 paramOne;
  1953.     UInt32 paramTwo;
  1954. };
  1955. typedef struct VDTimeDelays VDTimeDelays;
  1956. #if PRAGMA_ALIGN_SUPPORTED || __MWERKS__
  1957.     #pragma options align=reset
  1958. #endif
  1959. OSErr GDSetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr);
  1960. OSErr GDGetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr);
  1961.  
  1962. OSErr GDSetDelay(GDHandle device,Boolean dontWaitForVBL,double nanoseconds)
  1963. {
  1964.     OSErr error;
  1965.     VDTimeDelays timeDelays={0,0,0,0};
  1966.     
  1967.     timeDelays.validMask=gDontWaitForVBLMask;
  1968.     if(dontWaitForVBL)timeDelays.flags=gDontWaitForVBLMask;
  1969.     else timeDelays.flags=0;
  1970.     if(IsFinite(nanoseconds)){
  1971.         timeDelays.flags|=gSetCLUTTimingMask;
  1972.         timeDelays.validMask|=gSetCLUTTimingMask;
  1973.         timeDelays.paramOne=nanoseconds/0x10000/0x10000;
  1974.         timeDelays.paramTwo=nanoseconds-(double)timeDelays.paramOne*0x10000*0x10000;
  1975.     }else timeDelays.paramOne=timeDelays.paramTwo=0; 
  1976.     error=GDSetTimeDelays(device,&timeDelays);
  1977.     return error;
  1978. }
  1979. OSErr GDGetDelay(GDHandle device,Boolean *dontWaitForVBLPtr,double *nanosecondsPtr)
  1980. {
  1981.     OSErr error;
  1982.     VDTimeDelays timeDelays={0,0,0,0};
  1983.     
  1984.     timeDelays.validMask=gDontWaitForVBLMask|gSetCLUTTimingMask;
  1985.     error=GDGetTimeDelays(device,&timeDelays);
  1986.     if(error)return error;
  1987.     if(dontWaitForVBLPtr!=NULL){
  1988.         if(timeDelays.flags&gDontWaitForVBLMask) *dontWaitForVBLPtr=1;
  1989.         else *dontWaitForVBLPtr=0;
  1990.     }
  1991.     if(nanosecondsPtr!=NULL)
  1992.         *nanosecondsPtr=(double)timeDelays.paramTwo+(double)timeDelays.paramOne*0x10000*0x10000;
  1993.     return error;
  1994. }
  1995. OSErr GDSetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr)
  1996. {
  1997.     OSErr error;
  1998.     long stackSpace;
  1999.     
  2000.     stackSpace=StackSpace();
  2001.     if(device==NULL || (*device)->gdRefNum==0 || timeDelaysPtr==NULL) return controlErr;
  2002.     error=GDControl((*device)->gdRefNum,cscSetTimeDelays,(Ptr)timeDelaysPtr);
  2003.     stackSpace=StackSpace();
  2004.     return error;
  2005. }
  2006. OSErr GDGetTimeDelays(GDHandle device,VDTimeDelays *timeDelaysPtr)
  2007. {
  2008.     OSErr error;
  2009.     long stackSpace;
  2010.     
  2011.     stackSpace=StackSpace();
  2012.     if(device==NULL || (*device)->gdRefNum==0 || timeDelaysPtr==NULL) return statusErr;
  2013.     error=GDStatus((*device)->gdRefNum,cscGetTimeDelays,(Ptr)timeDelaysPtr);
  2014.     stackSpace=StackSpace();
  2015.     return error;
  2016. }
  2017.